<template>
	<view class="comm-input-warp">
		<up-input
			:placeholder="$t('login.comm.code')"
			border="false"
			:v-model="emailValue"
			:customStyle="inputCss"
			type="number"
			@change="updateValue"
		>
			<template #suffix>
				<view class="code-warp" v-if="countdown">
					<up-count-down :time="60 * 1000" format="ss" @finish="getCode(false)"></up-count-down> 
					<text style="margin-left: 10rpx;">s</text>
				</view>
				<view v-else class="code-warp" @click="getCode(true)">
					<view>{{$t('login.comm.get.code')}}</view>
				</view>
			</template>
		</up-input>
		<up-toast ref="uToastRef"></up-toast>
	</view>
</template>

<script>
	import { ref } from 'vue';
	import { getEmailCode } from '@/api/common.js'
	
	const uCodeRef = ref(null);
	
	export default {
		name: 'inputComm',
		props: ['codeNumberRef','type','modelValue'],
		watch: {
		},
		 
		data() {
			return {
				countdown:false,
				inputCss:{
					"height":'108rpx',
					"background": "#F3F3F3FF",
					"border-radius": "20rpx",
					"border": "0rpx",
					"padding": "0 16px",
				},
				emailValue:this.modelValue,
			}
		},
		emits: ['update:modelValue'],
		mounted() {
		},
		methods: {
			updateValue(value) {
				this.$emit('getCode',value);
			    // 触发input事件更新父组件绑定的值
			    this.$emit('update:modelValue', value);
			},
			/**
			 * 获取验证码
			 * @param {Object} val
			 */
			getCode(val){
				if(val){
					const codeNumber = this.codeNumberRef;
					if(codeNumber){
						this.getEmailCodeFun(codeNumber);
					}else{
						this.$refs.uToastRef.show({
							type: 'error',
							message: this.$t('login.comm.email'),
						});
						return;
					}
				}else{
					this.countdown = false;
				}
			},
			// 获取邮箱验证码
			async getEmailCodeFun(codeNumber){
				const params={
					email:codeNumber,
					type:this.type,
				}
				const response = await getEmailCode(params);
				console.log("response",response);
				if(response && response.bizcode === 100){
					// 便于测试环境测试
					if(response.data){
						console.log("response.data",response.data);
						this.emailValue = response.data;
						this.$emit('getCode',response.data);
					}
					this.countdown = true;
					this.$refs.uToastRef.show({
						type: 'success',
						message: response.msg,
					});
				}else{
					this.countdown = false;
				}
			},
		},
	};

</script>

<style lang="less" scoped>
	.code-warp{
		text-align: right;
		display: flex;
		justify-content: flex-end;
		font-weight: bold;
		font-size: 36rpx;
		color: #265FFF;
	}
	.wrap {
		padding: 24rpx;
	}
</style>